package cn.itcast.n8;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import static cn.itcast.n2.util.Sleeper.sleep;

@Slf4j(topic = "c.TestAqs")
public class TestAqs {

    public static void main(String[] args) {
        final ReentrantReadWriteLock writeLock = new ReentrantReadWriteLock();

        MyLock lock = new MyLock();
        new Thread(()->{
            lock.lock();
            log.debug("locking...");
//
//            lock.lock();
//            log.debug("locking...");
            try {
                log.debug("locking...");
                sleep(2);
            }finally {
                log.debug("unlocking...");
                lock.unlock();
            }
        },"t1").start();

        new Thread(()->{
            lock.lock();
            try {
                log.debug("locking...");
            }finally {
                log.debug("unlocking...");
                lock.unlock();
            }
        },"t2").start();
    }

}

class MyLock implements Lock{

    private MySync sync = new MySync();

    class MySync extends AbstractQueuedSynchronizer{
        @Override
        protected boolean tryAcquire(int arg) {
            if (compareAndSetState(0,1)) {
                //1.加上了锁,设置 owner 为当前线程
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        @Override
        protected boolean tryRelease(int arg) {
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }

        //是否持有独占锁
        @Override
        protected boolean isHeldExclusively() {
//            return getExclusiveOwnerThread() == Thread.currentThread();
            return getState() == 1;
        }

        public Condition newCondition(){
            return new ConditionObject();
        }

        final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                if (compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }
    }

    // 加锁（不成功进入等待队列）
    @Override
    public void lock() {
        sync.acquire(1);
    }

    // 加锁，可响应中断
    @Override
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    // 加锁，快速失败
    @Override
    public boolean tryLock() {
        return sync.tryAcquire(1);
    }

    // 加锁，指定等待时间
    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireNanos(1,unit.toNanos(time));
    }

    // 解锁
    @Override
    public void unlock() {
        sync.release(1);
    }

    // 新建条件队列
    @Override
    public Condition newCondition() {
        return sync.newCondition();
    }

}
